import csv
import os
import re

# 输出CSV文件路径
csv_file = '/root/jx_codes/crateGraph/csv'
# log_path
log_file_path='/root/jx_codes/crateGraph/log'
# 定义字段名称
field_names = ['Pid','Syscall']
def contains_null_character(line):
    return '\x00' in line
def switch_syscall(line,pid,time):
    # 0 is normal,1 is unfinished,2 is resumed
    flag=0
    if "resumed" in line:
        flag = 2
        syscall="-"
     # syscall ex:normal
    elif "+++" in line:
        syscall="-"
        flag=3
    elif "SIGCHLD" in line:
        syscall="-"
        flag=4
    elif "<unfinished ...>" in line:
        syscall=line.replace(time,"").replace(pid,"").replace("<unfinished ...>","").strip()
        syscall=syscall.split("(",1)[0]
        special_characters = re.findall(r'[^a-zA-Z0-9_]', syscall)
        if len(special_characters) !=0:
            flag = 2
            print(syscall)
            return flag ,syscall 
        if syscall == '---':
            # print(line)
            flag = 2
            return flag ,syscall 
        flag = 1
    else:
        syscall = line.split()[2].split("(")[0]
        special_characters = re.findall(r'[^a-zA-Z0-9_]', syscall)
        if len(special_characters) !=0:
            flag = 2
            print(syscall)
            return flag ,syscall 
        if syscall == '---':   
            # print(line)
            flag = 2
            return flag , syscall 
        flag = 0
    return flag,syscall

for file_name in os.listdir(log_file_path):
    if file_name.endswith('.log'):
        print(file_name)
        csv_name = file_name.replace('.log','')
        if 'benign' in file_name :
            csv_path=os.path.join(csv_file,csv_name+".csv")
        if 'malicious' in file_name:
            csv_path=os.path.join(csv_file,csv_name+".csv")
        log_path=os.path.join(log_file_path, file_name)
        print(csv_path)
    # 打开日志文件和CSV文件
        with open(log_path, 'r') as file, open(csv_path, 'w', newline='') as csv_output:
            # 创建CSV写入器
            writer = csv.writer(csv_output)
            # 写入字段名称
            writer.writerow(field_names)
            for line in file:
                if contains_null_character(line):  # 检查是否整行都是空格
                    continue
                line = line.strip()
                # PID
                pid = line.split()[0]
                # TIME
                time = line.split()[1]
                flag,syscall = switch_syscall(line,pid,time)
                if flag == 1 :
                    writer.writerow([pid,syscall])
                elif flag == 0 :
                    writer.writerow([pid,syscall])
                else :
                    continue